<template>
    <div>
        <div style="margin: 10px 0">
            <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search"
                      v-model="raceName"></el-input>
            <!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-message" class="ml-5" v-model="email"></el-input>-->
            <!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-position" class="ml-5" v-model="address"></el-input>-->
            <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
        </div>

        <div style="margin: 10px 0">
            <el-button type="primary" @click="handleAdd">创建赛事 <i class="el-icon-circle-plus-outline"></i></el-button>
            <el-popconfirm
                    class="ml-5"
                    confirm-button-text='确定'
                    cancel-button-text='我再想想'
                    icon="el-icon-info"
                    icon-color="red"
                    title="您确定批量删除这些数据吗？"
                    @confirm="delBatch">
                <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
            </el-popconfirm>
            <!--            <el-button-->
            <!--                    type="primary"-->
            <!--                    icon="el-icon-download"-->
            <!--                    @click="$root.downloadTemplate('数据表格.xlsx')">下载模板-->
            <!--            </el-button>-->
            <!--<el-upload action="http://localhost:9090/race/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block">
              <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
            </el-upload>
            <el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button>-->
        </div>

        <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
            <el-table-column prop="id" label="ID" v-if="false" width="80" sortable></el-table-column>
            <el-table-column prop="raceId" label="赛事id" v-if="false"></el-table-column>
            <el-table-column prop="raceType" label="赛事类型" :formatter="raceTypeFormatter"></el-table-column>
            <el-table-column prop="raceName" label="赛事名称"></el-table-column>
            <el-table-column prop="raceStation" label="分站"></el-table-column>
            <el-table-column prop="raceDate" label="赛事日期"></el-table-column>
            <el-table-column prop="racePosition" label="赛事地点"></el-table-column>
            <el-table-column prop="raceLevel" label="赛事级别"></el-table-column>

            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button type="text" @click="selectJudge(scope.row)">选派裁判</el-button>
                    <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-popconfirm
                            class="ml-5"
                            confirm-button-text='确定'
                            cancel-button-text='我再想想'
                            icon="el-icon-info"
                            icon-color="red"
                            title="您确定删除吗？"
                            @confirm="del(scope.row.id)"
                    >
                        <el-button type="text" slot="reference">删除</el-button>
                    </el-popconfirm>
                    <el-popover placement="bottom" width="150px" trigger="click">
                        <template #reference>
                            <el-button type="text">更多</el-button>
                        </template>
                        <div>
                            <el-button type="success" @click="generateLink(scope.row)">生成裁判报名链接</el-button>
                            <el-upload action="" :on-change="onChange" :show-file-list="false"
                                       accept="xlsx" :auto-upload="false"
                                       :on-success="handleExcelImportSuccess" style="display: inline-block">
                                <el-button type="success" @click="initRaceData(scope.row)">导入比赛结果</el-button>
                            </el-upload>
                            <el-button type="success" @click="generatePdf(scope.row)">生成技术官员名单</el-button>
                        </div>
                    </el-popover>

                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[2, 5, 10, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog title="创建赛事" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false">
            <el-form label-width="120px" size="small" style="width: 80%; margin: 0 auto">
                <el-form-item prop="raceId" label="赛事id" hidden>
                    <el-input v-model="form.raceId" autocomplete="off" readonly></el-input>
                </el-form-item>
                <el-form-item prop="raceType" label="赛事类型">
                    <el-select v-model="form.raceType" placeholder="请选择" @change="selectType(form.raceType)">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="raceName" label="赛事名称">
                    <el-input v-model="form.raceName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="raceStation" label="分站">
                    <el-input v-model="form.raceStation" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="raceDate" label="赛事日期">
                    <el-date-picker v-model="form.raceDate" type="daterange" value-format="yyyy/MM/dd"
                                    range-separator="-"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item prop="raceName" label="赛事地点">
                    <el-input v-model="form.racePosition" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="raceLevel" label="赛事级别">
                    <el-select v-model="form.raceLevel" placeholder="请选择">
                        <el-option
                                v-for="item in levels"
                                :key="item.type"
                                :label="item.level"
                                :value="item.level">
                        </el-option>
                    </el-select>
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :close-on-click-modal="false"
                   title="选派裁判员"
                   :visible.sync="dialogJudgeVisible"
                   top="30px"
                   center="true"
                   width="90%">
            <iframe style="width: 100%;height: 700px;margin-top: 10px;margin-top: -10px;" :src="url"></iframe>
        </el-dialog>
    </div>
</template>

<script>
    // import FileSaver from "file-saver";
    import * as XLSX from "xlsx"

    export default {
        name: "Race",
        data() {
            return {
                frontURL: "http://172.17.1.116:8080",
                tableData: [],
                total: 0,
                pageNum: 1,
                pageSize: 10,
                raceName: "",
                form: {},
                dialogFormVisible: false,
                dialogJudgeVisible: false,
                multipleSelection: [],
                user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
                options: [
                    {value: '0', label: '国内'},
                    {value: '1', label: '国际'}
                ],
                levels: [],
                url: '',
                raceData:{}
            }
        },
        created() {
            this.load()
        },
        methods: {
            load() {
                const data = {
                    "page": this.pageNum,
                    "pageSize": this.pageSize,
                    "raceName": this.raceName
                }
                this.request.post("/race/page", data).then(res => {
                    //this.tableData = res.data.records
                    this.tableData = res.data.data
                    this.total = res.data.total
                })
            },
            raceTypeFormatter(row) {
                if (row.raceType === "0") {
                    return "国内"
                } else {
                    return "国际"
                }

            },
            selectType(type) {
                const data = {
                    "type": type
                }
                this.request.post("/race/queryRaceLevels", data).then(res => {
                    if (res.code === 200) {
                        this.levels = res.data
                        // console.log(this.levels)
                        // this.form.raceLevel = ""
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            /**
             * 选派裁判
             */
            selectJudge(row) {
                this.dialogJudgeVisible = true
                this.url = this.frontURL + "/Judge?raceId=" + row.raceId
            },
            /**
             * 生成裁判报名链接
             */
            generateLink(row) {
                let str = this.frontURL + '/judgeLink?raceId=' + row.raceId + "&raceName=" + row.raceName
                this.$alert(str, '生成成功', {
                    confirmButtonText: '复制',
                    callback: action => {
                        let oInput = document.createElement('input')
                        oInput.value = str
                        document.body.appendChild(oInput)
                        oInput.select() // 选择对象
                        document.execCommand("Copy") // 执行浏览器复制命令
                        this.$message({
                            message: '复制成功',
                            type: 'success'
                        })
                        oInput.remove()
                    }
                });
            },
            onChange(file){
              this.importResult(file)
            },
            initRaceData(row){
                this.raceData = row
            },
            /**
             * 导入比赛结果
             */
            importResult(file) {
                if (!file) {
                    //如果没有文件
                    return false;
                } else if (!/.(xls|xlsx)$/.test(file.name.toLowerCase())) {
                    this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
                    return false;
                }
                const fileReader = new FileReader();
                fileReader.onload = (ev) => {
                    try {
                        const data = ev.target.result;
                        const workbook = XLSX.read(data, {
                            type: "binary",
                        });
                        if (workbook.SheetNames.length >= 1) {
                            this.$message({
                                message: "导入数据表格成功",
                                showClose: true,
                                type: "success",
                            });
                        }
                        const wsname = workbook.SheetNames[0]; //导入excel的第一张表
                        // 导入的信息
                        const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
                        let params = [];
                        //如果一行表头，则i从0开始，如果是两行则从1开始以此类推
                        for (let i = 0; i < ws.length; i++) {
                            let sheetData = {
                                // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
                                peoName: ws[i]["姓名"],
                                peoSex: ws[i]["性别"],
                                peoIdcard: ws[i]["证件号"],
                                peoUnit: ws[i]["所属单位"],
                                domesticLevel: ws[i]["国内级别"],
                                foreignLevel: ws[i]["国际级别"],
                                peoRank: ws[i]["名次"]
                            };
                            params.push(sheetData)
                        }
                        const data2 = {
                            "raceBean":params,
                            "raceType":this.raceData.raceType,
                            "raceName":this.raceData.raceName,
                            "raceStation":this.raceData.raceStation,
                            "raceDate":this.raceData.raceDate,
                            "raceAddress":this.raceData.racePosition,
                            "raceId":this.raceData.raceId,
                            "raceLevel":this.raceData.raceLevel
                        }
                        this.request.post("/race/import", data2).then(res => {
                            if (res.code === 200) {
                                this.levels = res.data
                                // console.log(this.levels)
                                // this.form.raceLevel = ""
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    } catch (e) {
                        return false;
                    }
                };
                // 如果为原生 input 则应是 files[0]
                fileReader.readAsBinaryString(file.raw);
            },
            generatePdf(row) {
                const data = {
                    "raceId": row.raceId,
                    "raceName": row.raceName,
                    "raceStation": row.raceStation
                }
                this.request.post("/race/generatePdf", JSON.stringify(data)).then(res => {
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        // let url = 'http://localhost:9090/rank/springboot/src/main/resources/wordToHtml/'+row.raceName+".pdf";
                        // let url = res.data.realUrl;
                        // this.request.post("/race/download",JSON.stringify({"url":url})).then(res => {
                        //     if (res.code === 200) {
                        //         this.$message.success(res.message)
                        //     } else {
                        //         this.$message.error(res.message)
                        //     }
                        // })
                        let url = res.data.pdfUrl;

                        window.open("http://172.17.1.116:9090/" + url);
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            save() {
                const level = this.form.raceLevel;
                let raceDate = '';
                raceDate = this.form.raceDate[0] + "-" + this.form.raceDate[1]
                this.form.raceDate = raceDate
                if (this.form.raceType === "0" && level.includes("G")) {
                    return this.$message.error("国内赛事不能选择国际赛事级别！")
                } else if (this.form.raceType === "1" && level.includes("C")) {
                    return this.$message.error("国际赛事不能选择国内赛事级别！")
                }
                this.request.post("/race/save", JSON.stringify(this.form)).then(res => {
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        this.dialogFormVisible = false
                        this.load()
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            handleAdd() {
                this.dialogFormVisible = true
                this.form = {}
                this.$nextTick(() => {
                    if (this.$refs.img) {
                        this.$refs.img.clearFiles();
                    }
                    if (this.$refs.file) {
                        this.$refs.file.clearFiles();
                    }
                })
            },
            handleEdit(row) {
                this.selectType(row.raceType)
                this.form = JSON.parse(JSON.stringify(row))
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    if (this.$refs.img) {
                        this.$refs.img.clearFiles();
                    }
                    if (this.$refs.file) {
                        this.$refs.file.clearFiles();
                    }
                })
            },
            del(id) {
                this.request.delete("/race/" + id).then(res => {
                    if (res.code === 200) {
                        this.$message.success("删除成功")
                        this.load()
                    } else {
                        this.$message.error("删除失败")
                    }
                })
            },
            handleSelectionChange(val) {
                console.log(val)
                this.multipleSelection = val
            },
            delBatch() {
                if (!this.multipleSelection.length) {
                    this.$message.error("请选择需要删除的数据")
                    return
                }
                let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
                this.request.post("/race/del/batch", ids).then(res => {
                    if (res.code === 200) {
                        this.$message.success("批量删除成功")
                        this.load()
                    } else {
                        this.$message.error("批量删除失败")
                    }
                })
            },
            reset() {
                this.raceName = ""
                this.load()
            },
            handleSizeChange(pageSize) {
                this.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                this.pageNum = pageNum
                this.load()
            },
            handleFileUploadSuccess(res) {
                this.form.file = res
            },
            handleImgUploadSuccess(res) {
                this.form.img = res
            },
            download(url) {
                window.open(url)
            },
            exp() {
                window.open("http://localhost:9090/race/export")
            },
            handleExcelImportSuccess() {
                this.$message.success("导入成功")
                this.load()
            }
        }
    }
</script>


<style>
    .headerBg {
        background: #eee !important;
    }

    .el-button {
        margin: 0px 6px 12px;
    }
</style>
